﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CpuSimulator.Instructions
{
    /// <summary>
    ///JALR(Jump And Link Register) 将rs1中的值加上立即数作为地址，将下一条命令的地址（PC+4）存放到rd，然后 将PC寄存器指向新地址
    /// _________________________________________________________________________________________________________________________________________________
    /// |_________________立即数12位________________________|_________rs1,5位______|_Func3______|_________rd,5位______|_____OPCODE 7位____________|
    /// | 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 | 15 | 14 | 13 | 12 | 11 | 10 | 09 | 08 | 07 | 06 | 05 | 04 | 03 | 02 | 01 | 00 |
    /// |                         imm[11:0]                                        |       rs1                     |    000          |        rd                      |            1100111                     |
    /// </summary>
    public class JALR : Instruction
    {
        public override void Execute(Cpu cpuinfo)
        {
            int address = cpuinfo.Registers[this.Rs1].Value + this.Immediate;
            //address = address & 0xfe; //将最后一位设成0，因为即使用压缩格式，命令开始的位置至少是2的倍数，不可能从单数地址开始
            var newVal = cpuinfo.PC.Value + 4;
            cpuinfo.Registers[this.Rd].SetValue(newVal);
            cpuinfo.PC.SetValue(address);
            cpuinfo.InvodeRegisterChange(this.Rd, newVal.ToString("X8"));
            cpuinfo.InvodeRegisterChange(cpuinfo.PC.Index, address.ToString("X8"));
        }
    }
}
